package algorithm;

import io.OutputWriter;
import io.PlinkFilereader;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

import pac.SearchDatastructure;
import datastructures.MapfileWrapper;
import datastructures.SNPInfo;


public class ApplyMap {

	private SearchDatastructure searcher;
	private OutputWriter outputter;
	private MapfileWrapper snpSet;

	
	public ApplyMap(SearchDatastructure I, OutputWriter O) throws IOException {
		searcher = I;
		outputter = O;
		snpSet = new MapfileWrapper(searcher.snpList);
	}
	
	/*
	 * Apply genetic map
	 */
	public void applyGeneticMap () throws IOException {	
		
		PlinkFilereader pf = new PlinkFilereader();
		Map<String, Double> snpToCm = pf.readGeneticMapfile(searcher.userParams.getGeneticMapFile());
		
		FileWriter fstream = new FileWriter( searcher.userParams.getStage2Output(), false );
		BufferedWriter bwriter = new BufferedWriter (fstream);
		
		SNPInfo[] mappedSNPs = new SNPInfo[snpSet.getNumberOfSNPs()];
		for(int index=0; index<snpSet.getNumberOfSNPs(); index++) 
		{
			mappedSNPs[index] = snpSet.getSNPInfo(index);
			Double cmdistance = snpToCm.get(mappedSNPs[index].getRsid());
			if ( cmdistance == null )
				cmdistance = 0.0;
			mappedSNPs[index].setCm_distance(cmdistance);
			bwriter.write(mappedSNPs[index].toStringMapFormat() + "\n");
			bwriter.flush();
		}
		
		System.out.println("Finished.");
		outputter.Close();
	}
	
	

	public boolean processValidPairs (int[] variables) {
			
			if(variables[0] == -1 || variables[1] == -1)
				return false;
			
			int order = variables.length;
			
			//2.5 : establish expected and observed on number of case carriers
			int[][][] noOfCaseCarriers = searcher.snpIndices.getObservedCaseCarriers(searcher.userParams, variables);
			double pvalueCaseOnly = searcher.significance.TestCasesOnly ( order, noOfCaseCarriers );
			
			int[][][] noOfControlCarriers = searcher.snpIndices.getObservedControlCarriers(searcher.userParams, variables);
			double pvalueCaseControl = searcher.significance.TestCasesVsControls ( order, noOfCaseCarriers, noOfControlCarriers );
			
			if ( 	(variables[0] == variables[1]) 
					|| (variables[0]-variables[1] == 1 && variables[0]%2==1 && variables[1]%2==0)
					|| (variables[1]-variables[0] == 1 && variables[1]%2==1 && variables[0]%2==0) 
				)
				pvalueCaseControl = 1;
				
			//depending on whether you are asked for a region, or for a list of specific entries, output accordingly.
			outputter.WriteOutput(variables, noOfCaseCarriers, pvalueCaseOnly, noOfControlCarriers, pvalueCaseControl);
			
			return true;
	}
	
	
}
